package org.code.mallspringboot.controller;

import org.code.mallspringboot.dto.FlashPromotionDto;
import org.code.mallspringboot.pojo.SmsFlashPromotion;
import org.code.mallspringboot.service.SmsFlashPromotionService;
import org.code.mallspringboot.vo.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/flash")
public class SmsFlashPromotionController {

    @Autowired
    private SmsFlashPromotionService smsFlashPromotionService;

    @GetMapping("/list")
    public CommonResult list(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,
                             @RequestParam(value = "pageSize",defaultValue = "5") int pageSize,
                             String keyword){

        List<SmsFlashPromotion> list = smsFlashPromotionService.selectPage(keyword, pageNum, pageSize);
        int total = smsFlashPromotionService.total(keyword);
        Map<String,Object> map = new HashMap<>();
        map.put("list" , list);
        map.put("total" , total);
        if (!map.isEmpty()){
            return CommonResult.success(map);
        }
        return CommonResult.failed("查询 + 分页失败!");
    }

    //添加活动
    @PostMapping("/create")
    public CommonResult create(@RequestBody FlashPromotionDto flashPromotionDto){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        flashPromotionDto.setStartDate2(simpleDateFormat.format(flashPromotionDto.getStartDate()));
        flashPromotionDto.setEndDate2(simpleDateFormat.format(flashPromotionDto.getEndDate()));
        if (smsFlashPromotionService.add(flashPromotionDto) > 0){
            return CommonResult.success("添加成功");
        }
        return CommonResult.failed("添加失败");
    }

    //修改上线/下线
    @PostMapping("/update/status/{id}")
    public CommonResult update_status(@PathVariable int id,int status){
        if (smsFlashPromotionService.update_status(id, status) > 0){
            return CommonResult.success("修改成功");
        }
        return CommonResult.failed("修改失败");
    }

    //修改
    @PostMapping("/update/{id}")
    public CommonResult update(@PathVariable int id,@RequestBody FlashPromotionDto flashPromotionDto){
        flashPromotionDto.setId(id);
        if (smsFlashPromotionService.update(flashPromotionDto) > 0){
            return CommonResult.success("修改成功");
        }
        return CommonResult.failed("修改失败");
    }

    //删除
    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable int id){
        if (smsFlashPromotionService.delete(id) > 0){
            return CommonResult.success("删除成功!");
        }
        return CommonResult.failed("删除失败!");
    }
}
